<?php

namespace App\Repository\Msq;

use App\DataStore\RedisGeneral;
use App\Model\Divistion\DivisionModel;
use App\Repository\Redis\DivisionRedis;
use App\Repository\RepositoryGeneral;
use Hyperf\Di\Annotation\Inject;

class DivisionMsq extends RepositoryGeneral
{
    #[Inject]
    private DivisionModel $divisionModel;

    public function getDivisions(){
        $res = RedisGeneral::getInc()->getOrganDivision(getOrganIdByOrganCode());
        if(empty($res)){
            $res = $this
                ->divisionModel
                ->withCustomCondition()
                ->get()
                ->toArray();
            DivisionRedis::getInc()->updateDivisions();
        }
        return $res;
    }

    public function getDivision(int $divisionId,array $select = ['*']){
        return $this->divisionModel
            ->withCustomCondition()
            ->select($select)
            ->where('id',$divisionId)
            ->first();
    }

    public function addDivisions(array $data){
        $info = $this->divisionModel
            ->withCustomCondition()
            ->where('division_name', $data['division_name'])
            ->where('division_type', $data['division_type'])
            ->exists();

        if ($info) {
            apiError('当前机构已存在');
        }

        if (!empty($data['parent_id'])) {
            $parentExists = $this->divisionModel
                ->withCustomCondition()
                ->where('id', $data['parent_id'])
                ->exists();

            if (!$parentExists) {
                apiError('父级id不存在');
            }
        }

        $data['organ_id'] = getOrganIdByOrganCode();
        $data['status'] = 1;

        $res = $this->divisionModel->create($data);

        if ($res->id) {
            DivisionRedis::getInc()->updateDivisions();
        }

        return [
            'division_id' => $res->id
        ];

    }

}